package com.dap.cms.governance.controller;

import com.dap.cms.governance.common.RequestHolder;
import com.dap.cms.governance.po.CmsApplicationFormPo;
import com.dap.cms.governance.po.CmsCheckInfoPo;
import com.dap.cms.governance.po.CmsComponentPo;
import com.dap.cms.governance.service.CmsApplicationFormService;
import com.dap.cms.governance.service.CmsCheckInfoService;
import com.dap.cms.governance.service.CmsComponentService;
import com.dap.cms.governance.util.BeanValidator;
import com.dap.cms.governance.vo.ApplicationFormVo;
import com.dap.dao.model.Order;
import com.dap.dao.model.QueryResult;
import com.fesine.commons.entity.Result;
import com.fesine.commons.enums.ResultEnum;
import com.fesine.commons.util.ResultUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @description: cms_application_form表对应的控制层类
 * @author: Fesine
 * @createTime:2018/09/19
 * @update:修改内容
 * @author: Fesine
 * @updateTime:2018/09/19
 */
@RestController
@RequestMapping("/v1")
public class CmsApplicationFormController {
    private static final Logger logger = LoggerFactory.getLogger(CmsApplicationFormController.class);
    @Autowired
    private CmsApplicationFormService cmsApplicationFormService;
    @Autowired
    private CmsComponentService cmsComponentService;
    @Autowired
    private CmsCheckInfoService cmsCheckInfoService;

    /**
     * 新增CmsApplicationFormPo
     *
     * @param cmsApplicationFormPo
     * @return result
     */
    @PostMapping("/cmsApplicationForm")
    @Transactional
    public Result addCmsApplicationForm(CmsApplicationFormPo cmsApplicationFormPo) {
        BeanValidator.check(cmsApplicationFormPo);
        //检查是否已存在该组件，避免重复申请
        Boolean flag = cmsApplicationFormService.checkCmsApplicationFormPo(cmsApplicationFormPo);
        if (!flag) {
            return ResultUtils.error(500, "组件接入申请已通过或正在审核中，请勿重复申请");
        }
        CmsComponentPo cmsComponentPo = new CmsComponentPo();
        cmsApplicationFormPo.setStatus(0);
        cmsComponentPo.setId(cmsApplicationFormPo.getComponentId());
        cmsComponentPo = cmsComponentService.get(cmsComponentPo);
        cmsApplicationFormPo.setComponentName(cmsComponentPo.getComponentName());
        try {
            cmsApplicationFormService.request(cmsApplicationFormPo);
            return ResultUtils.success(ResultEnum.CREATED, null);
        } catch (Exception e) {
            logger.error("新增失败", e);
            return ResultUtils.error(500, "新增失败");
        }
    }

    /**
     * 更新CmsApplicationFormPo
     *
     * @param cmsApplicationFormPo
     * @return result
     */
    @PutMapping("/cmsApplicationForm")
    public Result updateCmsApplicationForm(CmsApplicationFormPo cmsApplicationFormPo) {
        try {
            cmsApplicationFormService.update(cmsApplicationFormPo);
            return ResultUtils.success(ResultEnum.CREATED, null);
        } catch (Exception e) {
            logger.error("更新失败", e);
            return ResultUtils.error(500, "更新失败");
        }
    }

    /**
     * 删除CmsApplicationFormPo
     *
     * @param id
     * @return result
     */
    @DeleteMapping("/cmsApplicationForm/{id}")
    public Result deleteCmsApplicationForm(@PathVariable("id") Integer id) {
        CmsApplicationFormPo cmsApplicationFormPo = new CmsApplicationFormPo();
        cmsApplicationFormPo.setId(id);
        cmsApplicationFormService.delete(cmsApplicationFormPo);
        return ResultUtils.success(cmsApplicationFormPo);
    }

    /**
     * 查看CmsApplicationFormPo详情
     *
     * @param id
     * @return result
     */
    @GetMapping("/cmsApplicationForm/{id}")
    public Result getCmsApplicationForm(@PathVariable("id") Integer id) {
        CmsApplicationFormPo cmsApplicationFormPo = new CmsApplicationFormPo();
        cmsApplicationFormPo.setId(id);
        cmsApplicationFormPo = cmsApplicationFormService.get(cmsApplicationFormPo);
        return ResultUtils.success(cmsApplicationFormPo);
    }

    /**
     * 查询CmsApplicationFormPo列表
     *
     * @param cmsApplicationFormPo
     * @return result
     */
    @GetMapping("/cmsApplicationForms")
    public Result listAll(CmsApplicationFormPo cmsApplicationFormPo) {
        List<CmsApplicationFormPo> list = cmsApplicationFormService.listAll(cmsApplicationFormPo);
        return ResultUtils.success(list);
    }

    /**
     * 分页查询CmsApplicationFormPo列表
     *
     * @param cmsApplicationFormPo
     * @param pageIndex
     * @param pageSize
     * @return result
     */
    @GetMapping("/cmsApplicationForms/page")
    public Result listPage(CmsApplicationFormPo cmsApplicationFormPo, @RequestParam(value = "pageIndex",
            required = false, defaultValue = "1")
            Integer pageIndex, @RequestParam(value = "pageSize", required = false, defaultValue =
            "10") Integer pageSize) {
        //根据组件名
        if (StringUtils.isNotEmpty(cmsApplicationFormPo.getComponentName())) {
            cmsApplicationFormPo.setComponentName("%".concat(cmsApplicationFormPo.getComponentName())
                    .concat("%"));
        } else {
            cmsApplicationFormPo.setComponentName(null);
        }
        cmsApplicationFormPo.addOrder(Order.asc("status"));
        cmsApplicationFormPo.addOrder(Order.desc("id"));
        QueryResult<CmsApplicationFormPo> result = cmsApplicationFormService.listPage(cmsApplicationFormPo, pageIndex, pageSize);

        Map<String, Object> map = new HashMap(16);
        List<CmsApplicationFormPo> CmsApplicationFormPos = result.getResultlist();
        List<ApplicationFormVo> vos = new ArrayList<>();
        if (RequestHolder.getCurrentUser().getManagerFlag() == 1) {
            for (CmsApplicationFormPo po : CmsApplicationFormPos) {
                ApplicationFormVo applicationFormVo = new ApplicationFormVo();
                BeanUtils.copyProperties(po, applicationFormVo);
                applicationFormVo.setChecked(false);
                vos.add(applicationFormVo);
            }
        } else {
            for (CmsApplicationFormPo po : CmsApplicationFormPos) {
                CmsCheckInfoPo cmsCheckInfoPo = new CmsCheckInfoPo();
                cmsCheckInfoPo.setApplicationId(po.getId());
                cmsCheckInfoPo.setToUserType(RequestHolder.getCurrentUser().getManagerFlag());
                cmsCheckInfoPo = cmsCheckInfoService.get(cmsCheckInfoPo);
                ApplicationFormVo applicationFormVo = new ApplicationFormVo();
                BeanUtils.copyProperties(po, applicationFormVo);
                if (null == cmsCheckInfoPo) {
                    applicationFormVo.setChecked(false);
                } else {
                    applicationFormVo.setChecked(cmsCheckInfoPo.getHandingResult() == 0);
                }
                vos.add(applicationFormVo);
            }
        }
        long total = result.getTotalrecord();
        if (total > 0) {
            map.put("totalRecord", total);
            map.put("resultList", vos);
        }
        return ResultUtils.success(map);
    }
}

